<template>
  <div class="database-config-edit">
    <el-card>
      <div slot="header" class="card-header">
        <span>编辑数据库配置</span>
      </div>
      
      <div class="form-container" v-if="form.id">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-collapse v-model="activeNames">
            <el-collapse-item title="基础配置" name="0">
              <el-form-item label="所属设备" prop="deviceId">
                <el-select v-model="form.deviceId" placeholder="请选择所属设备" style="width: 100%">
                  <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName" :value="device.id"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="配置名称" prop="configName">
                <el-input v-model="form.configName" placeholder="请输入配置名称"></el-input>
              </el-form-item>
              
              <el-form-item label="数据库类型" prop="dbType">
                <el-select v-model="form.dbType" placeholder="请选择数据库类型">
                  <el-option label="MySQL" value="MySQL"></el-option>
                  <el-option label="Oracle" value="Oracle"></el-option>
                  <el-option label="SQL Server" value="SQL Server"></el-option>
                  <el-option label="PostgreSQL" value="PostgreSQL"></el-option>
                  <el-option label="MongoDB" value="MongoDB"></el-option>
                </el-select>
              </el-form-item>
              
              <el-form-item label="数据库URL" prop="url">
                <el-input v-model="form.url" placeholder="请输入数据库URL" type="textarea" :rows="2"></el-input>
              </el-form-item>
              
              <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              
              <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" placeholder="请输入密码" :type="showPassword ? 'text' : 'password'">
                  <i slot="suffix" class="el-input__icon" @click="showPassword = !showPassword">
                    <i v-if="showPassword" class="el-icon-view"></i>
                    <i v-else><svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7 2C4.24 2 2 4.24 2 7C2 9.76 4.24 12 7 12C9.76 12 12 9.76 12 7C12 4.24 9.76 2 7 2ZM7 10.5C5.07 10.5 3.5 8.93 3.5 7C3.5 5.07 5.07 3.5 7 3.5C8.93 3.5 10.5 5.07 10.5 7C10.5 8.93 8.93 10.5 7 10.5Z" fill="currentColor"/><path d="M3.5 7H10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg></i>
                  </i>
                </el-input>
              </el-form-item>
              
              <el-form-item label="驱动类名" prop="driverClassName">
                <el-input v-model="form.driverClassName" placeholder="请输入驱动类名"></el-input>
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="高级配置" name="1">
              <el-form-item label="最大连接数" prop="maximumPoolSize">
                <el-input v-model.number="form.maximumPoolSize" placeholder="请输入最大连接数" type="number"></el-input>
              </el-form-item>
              
              <el-form-item label="最小空闲连接数" prop="minimumIdle">
                <el-input v-model.number="form.minimumIdle" placeholder="请输入最小空闲连接数" type="number"></el-input>
              </el-form-item>
              
              <el-form-item label="连接超时时间(ms)" prop="connectionTimeout">
                <el-input v-model.number="form.connectionTimeout" placeholder="请输入连接超时时间" type="number"></el-input>
              </el-form-item>
              
              <el-form-item label="空闲超时时间(ms)" prop="idleTimeout">
                <el-input v-model.number="form.idleTimeout" placeholder="请输入空闲超时时间" type="number"></el-input>
              </el-form-item>
              
              <el-form-item label="最大生命周期(ms)" prop="maxLifetime">
                <el-input v-model.number="form.maxLifetime" placeholder="请输入最大生命周期" type="number"></el-input>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
          
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <div v-else>
        <el-empty description="加载配置信息失败" />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'DatabaseConfigEdit',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    // 自定义验证规则
    const validateConfigName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入配置名称'));
      } else {
        // 检查配置名称是否已存在（排除当前配置）
        this.$api.databaseConfigApi.checkName(value).then(res => {
          const data = res && res.data || null;
          if (data && data.id !== this.form.id) {
            callback(new Error('配置名称已存在'));
          } else {
            callback();
          }
        }).catch(() => {
          // 如果请求失败（例如404），说明配置名称不存在，可以继续
          callback();
        });
      }
    };

    return {
      form: {
        id: null,
        configName: '',
        dbType: 'MySQL',
        url: '',
        username: '',
        password: '',
        driverClassName: '',
        maximumPoolSize: 10,
        minimumIdle: 5,
        connectionTimeout: 30000,
        idleTimeout: 600000,
        maxLifetime: 1800000,
        deviceId: ''
      },
      showPassword: false,
      activeNames: ['0'],
      deviceList: [],
      rules: {
        configName: [
          { validator: validateConfigName, trigger: 'blur' }
        ],
        dbType: [
          { required: true, message: '请选择数据库类型', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请输入数据库URL', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        driverClassName: [
          { required: true, message: '请输入驱动类名', trigger: 'blur' }
        ],
        deviceId: [
          { required: true, message: '请选择所属设备', trigger: 'change' }
        ],
        maximumPoolSize: [
          { required: true, message: '请输入最大连接数', trigger: 'blur' },
          { type: 'number', min: 1, message: '最大连接数必须大于0', trigger: 'blur' }
        ],
        minimumIdle: [
          { required: true, message: '请输入最小空闲连接数', trigger: 'blur' },
          { type: 'number', min: 0, message: '最小空闲连接数不能小于0', trigger: 'blur' }
        ],
        connectionTimeout: [
          { required: true, message: '请输入连接超时时间', trigger: 'blur' },
          { type: 'number', min: 1, message: '连接超时时间必须大于0', trigger: 'blur' }
        ],
        idleTimeout: [
          { required: true, message: '请输入空闲超时时间', trigger: 'blur' },
          { type: 'number', min: 1, message: '空闲超时时间必须大于0', trigger: 'blur' }
        ],
        maxLifetime: [
          { required: true, message: '请输入最大生命周期', trigger: 'blur' },
          { type: 'number', min: 1, message: '最大生命周期必须大于0', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    // 加载设备列表
    loadDeviceList() {
      this.$api.deviceApi.getAll().then(res => {
        const data = res && res.data || [];
        this.deviceList = data;
      }).catch(err => {
        console.error('获取设备列表失败:', err);
        this.$message.error('获取设备列表失败');
        this.deviceList = [];
      });
    },
    
    // 获取配置信息
    getConfigInfo() {
      this.$api.databaseConfigApi.getById(this.id).then(res => {
        const data = res && res.data || null;
        if (data) {
          // 深拷贝，避免直接修改响应数据
          this.form = { ...data };
        } else {
          this.$message.error('获取配置信息失败');
          this.$router.push('/database-config');
        }
      }).catch(err => {
        console.error('获取数据库配置失败:', err);
        this.$message.error('获取配置信息失败');
        this.$router.push('/database-config');
      });
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$api.databaseConfigApi.update(this.form.id, this.form).then(() => {
            this.$message.success('更新成功');
            this.$router.push('/database-config');
          }).catch(err => {
            console.error('更新数据库配置失败:', err);
            this.$message.error('更新失败');
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    
    // 取消操作
    handleCancel() {
      this.$router.push('/database-config');
    }
  },
  mounted() {
    this.loadDeviceList();
    this.getConfigInfo();
  }
};
</script>

<style scoped>
.database-config-edit {
  padding: 0;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>